<template>
	<view class="Wrapper">
		<navBar title="签字"></navBar>

		<view class="signature-page">
			<!-- 画布区域 -->
			<canvas
				class="signature-canvas"
				canvas-id="signatureCanvas"
				id="signatureCanvas"
				@touchstart="handleTouchStart"
				@touchmove="handleTouchMove"
				@touchend="handleTouchEnd"
				disable-scroll
				type="2d"></canvas>

			<!-- 顶部提示文字 -->
			<view class="top-tip"> 注意事项：请从左至右进行签署 </view>

			<!-- 底部按钮组 -->
			<view class="bottom-btns">
				<button class="btn return-btn" @click="goBack">返回</button>
				<view class="action-btns">
					<button class="btn clear-btn" @click="clearCanvas">重签</button>
					<button class="btn save-btn" @click="saveSignature">确认</button>
				</view>
			</view>
		</view>

		<!-- 添加隐藏的临时canvas -->
		<canvas
			canvas-id="tempCanvas"
			id="tempCanvas"
			style="position: fixed; left: -9999px; width: 2000px; height: 2000px"></canvas>
	</view>
</template>

<script setup>
	import { ref } from 'vue';
	import { onShow } from '@dcloudio/uni-app';

	const context = ref(null);
	const canvasId = ref(null);
	const canvas = ref(null);
	const isDrawing = ref(false);
	let lastX = 0;
	let lastY = 0;

	onShow(() => {
		// #ifdef H5
		context.value = uni.createCanvasContext('signatureCanvas');
		context.value.lineCap = 'round';
		context.value.lineWidth = 3;
		context.value.strokeStyle = '#000000';
		// #endif

		// #ifdef MP-WEIXIN
		const query = uni.createSelectorQuery();
		query
			.select('#signatureCanvas')
			.fields({ node: true, size: true })
			.exec((res) => {
				if (res[0]) {
					const canvas = res[0].node;
					context.value = canvas.getContext('2d');

					// 设置画布大小
					const dpr = uni.getWindowInfo().pixelRatio;
					canvas.width = res[0].width * dpr;
					canvas.height = res[0].height * dpr;

					// 设置画笔样式
					context.value.scale(dpr, dpr);
					context.value.lineCap = 'round';
					context.value.lineWidth = 3;
					context.value.strokeStyle = '#000000';
				}
			});
		// #endif
	});

	// 开始绘制
	const handleTouchStart = (e) => {
		isDrawing.value = true;
		const touch = e.touches[0];
		lastX = touch.x;
		lastY = touch.y;

		// #ifdef H5
		context.value.beginPath();

		context.value.moveTo(lastX, lastY);
		// #endif
	};

	// 绘制中
	const handleTouchMove = (e) => {
		if (!isDrawing.value) return;

		const touch = e.touches[0];

		// #ifdef H5
		context.value.beginPath();

		context.value.moveTo(lastX, lastY);
		context.value.lineTo(touch.x, touch.y);
		context.value.stroke();
		context.value.draw(true);
		lastX = touch.x;
		lastY = touch.y;
		// #endif

		// #ifdef MP-WEIXIN
		context.value.beginPath();
		context.value.moveTo(lastX, lastY);
		context.value.lineTo(touch.x, touch.y);
		context.value.stroke();
		lastX = touch.x;
		lastY = touch.y;
		// #endif
	};

	// 结束绘制
	const handleTouchEnd = () => {
		isDrawing.value = false;
	};

	// 清除画布
	const clearCanvas = () => {
		// #ifdef H5
		context.value.clearRect(0, 0, 1000, 1000); // 使用更大的尺寸确清除
		context.value.draw(true);
		// #endif

		// #ifdef MP-WEIXIN
		const canvas = context.value.canvas;
		context.value.clearRect(0, 0, canvas.width, canvas.height);
		// #endif
	};

	// 保存签名
	const saveSignature = () => {
		// #ifdef H5
		context.value.draw(true, () => {
			uni.canvasToTempFilePath({
				canvasId: 'signatureCanvas',
				success: (res) => {
					// 创建临时canvas进行旋转
					rotateImage(res.tempFilePath, (rotatedPath) => {
						uni.showToast({
							title: '保存成功',
							icon: 'success',
							complete: () => {
								const pages = getCurrentPages();
								const prevPage = pages[pages.length - 2];
								if (prevPage) {
									uni.$emit('signatureImage', {
										path: rotatedPath,
									});
									setTimeout(() => {
										uni.navigateBack();
									}, 500);
								}
							},
						});
					});
				},
				fail: (err) => {
					uni.showToast({
						title: '保存失败',
						icon: 'error',
					});
				},
			});
		});
		// #endif

		// #ifdef MP-WEIXIN
		const query = uni.createSelectorQuery();
		query
			.select('#signatureCanvas')
			.fields({ node: true, size: true })
			.exec((res) => {
				if (res[0]) {
					const canvas = res[0].node;
					uni.canvasToTempFilePath(
						{
							canvas: canvas,
							success: (res) => {
								// 创建临时canvas进行旋转
								rotateImage(res.tempFilePath, (rotatedPath) => {
									uni.showToast({
										title: '保存成功',
										icon: 'success',
										complete: () => {
											const pages = getCurrentPages();
											const prevPage = pages[pages.length - 2];
											if (prevPage) {
												uni.$emit('signatureImage', {
													path: rotatedPath,
												});
												setTimeout(() => {
													uni.navigateBack();
												}, 500);
											}
										},
									});
								});
							},
							fail: (err) => {
								uni.showToast({
									title: '保存失败',
									icon: 'error',
								});
							},
						},
						this
					);
				}
			});
		// #endif
	};

	// 添加旋转图片的函数
	const rotateImage = (tempFilePath, callback) => {
		uni.getImageInfo({
			src: tempFilePath,
			success: (imageInfo) => {
				const ctx = uni.createCanvasContext('tempCanvas');

				// 交换宽高
				const canvasWidth = imageInfo.height;
				const canvasHeight = imageInfo.width;

				// 清空画布并设置背景为白色
				ctx.fillStyle = '#FFFFFF';
				ctx.fillRect(0, 0, canvasWidth, canvasHeight);

				// 移动到画布中心
				ctx.translate(canvasWidth / 2, canvasHeight / 2);

				// 逆时针旋转90度
				ctx.rotate((-90 * Math.PI) / 180);

				// 将图片绘制到旋转后的位置
				ctx.drawImage(
					tempFilePath,
					-imageInfo.width / 2, // 向左偏移半个图片宽度
					-imageInfo.height / 2, // 向上偏移半个图片高度
					imageInfo.width,
					imageInfo.height
				);

				ctx.draw(false, () => {
					setTimeout(() => {
						uni.canvasToTempFilePath({
							canvasId: 'tempCanvas',
							width: canvasWidth,
							height: canvasHeight,
							destWidth: canvasWidth,
							destHeight: canvasHeight,
							fileType: 'png',
							quality: 1,
							success: (res) => {
								callback(res.tempFilePath);
							},
							fail: (err) => {
								console.error('旋转图片失败:', err);
								callback(tempFilePath);
							},
						});
					}, 300);
				});
			},
			fail: (err) => {
				console.error('获取图片信息失败:', err);
				callback(tempFilePath);
			},
		});
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};
</script>

<style scoped>
	.Wrapper {
		width: 100vw;
		height: 100vh;
		position: relative;
		display: flex;
		flex-direction: column;
		overflow: hidden;
	}
	.signature-page {
		width: 100%;
		flex: 1;
		background-color: #f6f7fb;
		position: relative;
	}

	.signature-canvas {
		width: 100%;

		position: absolute;
		width: 100%;
		height: 100%;
		left: 0;
		top: 0;
		z-index: 1;
	}

	.top-tip {
		position: absolute;
		top: 220rpx;
		right: -140rpx;
		text-align: center;
		color: #999;
		font-size: 14px;
		z-index: 2;
		transform: rotate(90deg);
	}

	.bottom-btns {
		position: absolute;
		height: 100%;

		left: 10px;
		padding: 100rpx 0;
		z-index: 2;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		box-sizing: border-box;
	}

	.btn {
		width: 90px;
		height: 40px;
		border-radius: 8px;
		font-size: 14px;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0;
		padding: 0;
		transform: rotate(90deg);
	}

	.return-btn {
		background-color: #ffffff;
		color: #333;
	}

	.action-btns {
		gap: 15px;
	}

	.clear-btn {
		background-color: #ffa500;
		color: #ffffff;
	}

	.save-btn {
		background-color: #007aff;
		color: #ffffff;
		margin-top: 160rpx;
	}

	/* 移除按钮的默认边框 */
	.btn::after {
		border: none;
	}
</style>
